#!/usr/bin/python
# Created by Juan C. Espinoza <jucar.espinoza@gmail.com> January 25, 2010

import os, gzip
from glob import glob
import argparse
from lisn_utils import *

sql = MySQL('10.10.16.1','gps','nova2013','lisn')

def main():
    '''
    '''
    # parse command line options
    parser = argparse.ArgumentParser(description=main.func_doc)
    # add options and arguments
    parser.add_argument('date', nargs='?', default=None,
        help='date to be updated fmt:yy,mm,dd')
    parser.add_argument('-i', '--instrument', action='store',
        help='Instrument')
    parser.add_argument('-y', '--yesterday', action='store_true',
        help='Update files from yesterday')

    args = parser.parse_args()

    if args.date is not None:
        dt = GPSDateTime(args.date)
    else:
        dt = GPSDateTime()

    if args.yesterday:
        dt = dt-timedelta(1)

    if args.instrument is None:
        data = sql.select('data,datatypes', ['alias','iddata','path','filename','idinstrument','data.iddatatype'], 
                          "datatypes.iddatatype=data.iddatatype")
    else:
        data = sql.select('data,datatypes,instruments', ['alias','iddata','path','filename','data.idinstrument','data.iddatatype'],
                          "datatypes.iddatatype=data.iddatatype AND data.idinstrument=instruments.idinstrument AND instruments.instrument='%s'" % args.instrument)
    for tup in data:
        path = dt.strftime(tup['path'])
        filename,i,j = dt.strftime(tup['filename']).split(',')
        files = glob(os.path.join(path, '*%s*' % filename))
        if files:
            xml = MyXML(sql.select_one('data','dates',['iddata'],[tup['iddata']]))
            if xml.add_date(dt.year,dt.month,dt.day):
                print 'Updating %s - %s' % (tup['iddata'],tup['alias'])
                sql.update('data',['dates'],[xml.tostring(False)],"iddata=%s" % tup['iddata'])
        #break

#Execute main routine
if __name__ == "__main__":
    main()
